import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { setCity } from "../../store/CitySliceReducer";
import { NavBar, Card, Tag, IndexBar, List } from "antd-mobile";
import { LocationFill } from "antd-mobile-icons";
import axios from "axios";
import styles from "./city.module.css";

function Index() {
  const { type } = useParams();
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const [cityList, setCityList] = useState([]);
  const [hotCity, setHotCity] = useState([]);
  const [curCity, setCurCity] = useState("");

  // 获取城市列表、热门城市、当前城市方法
  const getCityList = async () => {
    const res = await axios.get("/xx/city");
    const res2 = await axios.get("/xx/city/location", {
      params: {
        key: "c6eecbbeea56378e9be5f0120d56fa3f",
      },
    });
    setCurCity(res2.data.data.city);
    setCityList(res.data.data.cityList);
    setHotCity(res.data.data.hotCities);
  };

  useEffect(() => {
    getCityList();
  }, []);

  //点击城市选择
  const handelSelCity = (city) => {
    //调用仓库方法，修改城市数据
    dispatch(setCity({ type, city }));
    navigate("/");
  };

  return (
    <div>
      <NavBar
        style={{
          "--height": "50px",
          "--border-bottom": "1px #eee solid",
        }}
        onBack={() => navigate("/")}
      >
        城市选择
      </NavBar>
      <div>
        <Card
          title={
            <div>
              当前城市：
              <LocationFill color="#43aef3" /> {curCity}
            </div>
          }
        ></Card>
        <Card title="热门城市" className={styles.hotWrap}>
          {hotCity.length > 0 &&
            hotCity.map((item, index) => {
              return <Tag key={index}>{item.name}</Tag>;
            })}
        </Card>
      </div>
      <div style={{ height: window.innerHeight }}>
        <IndexBar>
          {cityList.length > 0 &&
            cityList.map((group) => {
              const { title, items } = group;
              return (
                <IndexBar.Panel
                  index={title}
                  title={`${title}`}
                  key={`${title}`}
                >
                  <List>
                    {items.map((item, index) => (
                      <List.Item
                        key={index}
                        onClick={() => handelSelCity(item.name)}
                      >
                        {item.name}
                      </List.Item>
                    ))}
                  </List>
                </IndexBar.Panel>
              );
            })}
        </IndexBar>
      </div>
    </div>
  );
}

export default Index;
